package com.msu.nava.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.msu.nava.MainActivity;
import com.msu.nava.R;
import com.msu.nava.alipay.PayResult;
import com.msu.nava.consts.URLs;
import com.msu.nava.modle.AnswerSheet;
import com.msu.nava.modle.SickDetailItem;
import com.msu.nava.util.GsonUtil;
import com.msu.nava.util.HttpUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 诊断activity，根据之前选择的病症选择对应的id
 */
public class DiagnoseActivity extends BaseActivity {
  private static final String TAG = "DiagnoseActivity";
  private static final String ORDERURL = URLs.REMOTE_ORDER;
  private static final String SYURL = URLs.REMOTE_SY;

  private int sickId;
  private ImageButton backButton;
  private Button submitButton;
  private String illname;
  private LinearLayout layout;
  private ProgressDialog progressDialog = null;
  private TextView sickTittle;
  private List<RadioGroup> groups;

  //以下是支付宝支付的相关参数
  private String orderInfo;
  private static final int SDK_PAY_FLAG = 1;
  private static final int SDK_AUTH_FLAG = 2;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_PROGRESS);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.activity_diagnose);
    initQuestionary();
  }

  @Override
  protected void onPause() {
    super.onPause();
    if (progressDialog != null && !this.isFinishing()) {
      progressDialog.dismiss();
    }
  }

  //新的初始化代码,和initView()类似
  private void initQuestionary() {
    Intent intent = getIntent();
    //从上一个activity中获取病名
    String iname = intent.getStringExtra("iname");
    illname = iname;
    Log.d(TAG, "initQuestionary: " + iname);
    groups = new ArrayList<>();
    layout = (LinearLayout) findViewById(R.id.sc);
    //添加标题
    sickTittle = new TextView(DiagnoseActivity.this);
    sickTittle.setText(iname);
    sickTittle.setTextSize(24);
    sickTittle.setTextColor(getResources().getColor(R.color.blue_light));
    sickTittle.setGravity(Gravity.CENTER);
    layout.addView(sickTittle);
    //查询服务器,local是本地测试，上线时需要使用remote
    //  queryFromServer(REMOTEURL);
    queryFromServer(SYURL, iname);
    backButton = (ImageButton) findViewById(R.id.titte_back);
    backButton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        //返回上个activity
        intent2Activity(MainActivity.class);
      }
    });
  }

  //最初版本的初始化代码
  private void initView() {

    Intent intent = getIntent();
    sickId = intent.getIntExtra("sickid", -1);
    switch (sickId) {
      case 0://感冒
        illname = "感冒";
        break;
      case 1://胃痛
        illname = "胃痛";
        break;
      case 2://腹泻
        illname = "腹泻";
        break;
      case 3://腹痛
        illname = "腹痛";
        break;
      case 4://不寐
        illname = "不寐";
        break;
    }
    groups = new ArrayList<>();
    layout = (LinearLayout) findViewById(R.id.sc);
    //添加标题
    sickTittle = new TextView(DiagnoseActivity.this);
    sickTittle.setText(illname);
    layout.addView(sickTittle);
    //查询服务器,local是本地测试，上线时需要使用remote
    //  queryFromServer(REMOTEURL);
    queryFromServer(SYURL, illname);
    backButton = (ImageButton) findViewById(R.id.titte_back);
    backButton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        //返回上个activity
        intent2Activity(MainActivity.class);
      }
    });
  }

  private void queryFromServer(String address, String illname) {

    showProgressDialog();
    HttpUtil.sendQuestionnaireRequest(address, illname, new Callback() {
      @Override
      public void onFailure(Call call, IOException e) {
        Log.d("qserr", "获取问卷失败:" + e.getMessage());
        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            closeProgressDialog();
            Toast.makeText(DiagnoseActivity.this, "加载失败,请查看网络连接", Toast.LENGTH_SHORT).show();
          }
        });

      }

      @Override
      public void onResponse(Call call, Response response) throws IOException {
        final String text = response.body().string();
        Log.d("symptoms", "返回的数据:" + text);
        final List<SickDetailItem> items = GsonUtil.toSickDetailItems(text);

        //成功获取到了数据
        if (items != null && items.size() != 0) {
          runOnUiThread(new Runnable() {
            @Override
            public void run() {
              closeProgressDialog();
              showQuestionnaire(items);//生成问卷
              //Toast.makeText(DiagnoseActivity.this, "请求成功！", Toast.LENGTH_SHORT).show();
            }
          });
        }
      }
    });
  }

  /**
   * 从服务端获取订单信息
   */
  private synchronized void getOrderInfoFromServer() {
    System.out.println("发送订单请求");
    showProgressDialog();

    HttpUtil.getOrferInfoFromServer(ORDERURL, new Callback() {
      @Override
      public void onFailure(Call call, IOException e) {
        System.out.println("获取订单失败");
        Log.d(TAG, "onFailure: ");
        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            closeProgressDialog();
            Toast.makeText(DiagnoseActivity.this, "加载失败", Toast.LENGTH_SHORT).show();
          }
        });
      }

      @Override
      public void onResponse(Call call, Response response) throws IOException {
        //获取签名后的订单信息
        System.out.println("获取订单成功");
        final String text = response.body().string();
        Log.d("orderi", "onResponse: " + text);
        orderInfo = text;
        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            closeProgressDialog();
            Toast.makeText(DiagnoseActivity.this, "获取订单信息成功", Toast.LENGTH_SHORT).show();
          }
        });

      }
    });

  }

  /**
   * 支付宝支付业务
   *
   * @param v
   */
  public synchronized  void payV2(View v) {
    int t=0;
    getOrderInfoFromServer();//若此方法执行成功，则已经获取到orderinfo
    if(orderInfo == null){
      Log.d("getoinfo", "payV2: get orderinfo again~!");
      getOrderInfoFromServer();
      t++;
      if(t>3){
        Toast.makeText(DiagnoseActivity.this, "网络异常，请重试", Toast.LENGTH_SHORT).show();
        return;
      }
    }


    try {
      wait(150);//等待回调函数的执行，否则orderinfo可能会为空
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    Log.i("getoinfo", "payV2: out " + orderInfo);
    Runnable payRunnable = new Runnable() {

      @Override
      public void run() {
        PayTask alipay = new PayTask(DiagnoseActivity.this);
        Log.i("getoinfo", "payV2: in " + orderInfo);
        Map<String, String> result = alipay.payV2(orderInfo, true);
        Log.i("msp", result.toString());

        Message msg = new Message();
        msg.what = SDK_PAY_FLAG;
        msg.obj = result;
        mHandler.sendMessage(msg);
      }
    };

    Thread payThread = new Thread(payRunnable);
    payThread.start();
  }

  @SuppressLint("HandlerLeak")
  private Handler mHandler = new Handler() {
    @SuppressWarnings("unused")
    public void handleMessage(Message msg) {
      switch (msg.what) {
        case SDK_PAY_FLAG: {
          @SuppressWarnings("unchecked")
          PayResult payResult = new PayResult((Map<String, String>) msg.obj);
          /**
           对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
           */
          String resultInfo = payResult.getResult();// 同步返回需要验证的信息
          String resultStatus = payResult.getResultStatus();
          // 判断resultStatus 为9000则代表支付成功
          if (TextUtils.equals(resultStatus, "9000")) {
            // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
            Toast.makeText(DiagnoseActivity.this, "支付成功,即将获取诊断结果", Toast.LENGTH_SHORT).show();
            Set<Integer> userSympoms = new TreeSet<>();
            for (RadioGroup gp : groups) {
              userSympoms.add(gp.getCheckedRadioButtonId());//获取用户输入
            }
            //用AnswerSheet代替ViewObject
            AnswerSheet userAnswerSheet = new AnswerSheet();
            userAnswerSheet.setIllname(illname);
            userAnswerSheet.setUs(userSympoms);
            //发送问卷
            intent2Activity(ResultActivity.class, userAnswerSheet);

          } else {
            // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
            Toast.makeText(DiagnoseActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
          }
          break;
        }
      }
    }

    ;
  };


  private void showQuestionnaire(List<SickDetailItem> items) {
    if (items.size() != 0) {
      Log.d("qssuc", "get Qs success~!");
      for (SickDetailItem item : items) {
        TextView sname = new TextView(DiagnoseActivity.this);
        sname.setText(item.getSickname());//设置选项的名字
        int size = item.getSdId().size();
        RadioGroup rg = new RadioGroup(DiagnoseActivity.this);

        for (int i = 0; i < size; i++) {
          RadioButton spbtn = new RadioButton(DiagnoseActivity.this);
          spbtn.setText(item.getSdPerformance().get(i));//设置单选按钮的名字
          spbtn.setId(item.getSdId().get(i));//设置按钮的id为数据库中的id（主键）
          rg.addView(spbtn, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        }
        rg.setOrientation(LinearLayout.HORIZONTAL);//横向布局
        //把组件添加进入layout，完成一个选项的动态添加
        layout.addView(sname, LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layout.addView(rg, LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        //把一个radioGroup放入到list中，方便后面读取
        groups.add(rg);
      }
    } else {
      //todo
      sickTittle.setText("网络错误,请重试");
    }
    //设置提交按钮
    submitButton = new Button(DiagnoseActivity.this);
    submitButton.setText("提     交");
    //设置文本大小
    submitButton.setTextSize(25);
    //设置圆角背景
    submitButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.yuanjiao));
    //设置文本颜色
    submitButton.setTextColor(getResources().getColor(R.color.white));
    //设置文本位置
    submitButton.setGravity(Gravity.CENTER);

    submitButton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        //在handler里面提交问卷
        //payV2(v);
        AlertDialog dialog = new AlertDialog.Builder(DiagnoseActivity.this)
          .setTitle("确认")
          .setMessage("查看结果需收取两元手续费。确认？")
          .setPositiveButton(R.string.comfirm, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
              payV2(getWindow().getDecorView());
            }
          })
          .setNegativeButton(R.string.cancel, null)
          .create();
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.setWindowAnimations(R.style.PopupAnimation);
        dialog.show();
      }
    });
    layout.addView(submitButton);

  }

  /**
   * 显示进度对话框
   */
  private void showProgressDialog() {
    if (progressDialog == null) {
      progressDialog = new ProgressDialog(DiagnoseActivity.this);
      progressDialog.setMessage("正在加载...");
      progressDialog.setCanceledOnTouchOutside(false);
    }
    progressDialog.show();
  }

  /**
   * 关闭进度对话框
   */
  private void closeProgressDialog() {
    if (progressDialog != null) {
      progressDialog.dismiss();
    }
  }


}
